package tutorial;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import com.opensymphony.xwork2.ActionSupport;

public class login extends ActionSupport {
	private String username;
	private String password;
	/*private String driver = "com.mysql.jdbc.Driver";
	private String URL = "jdbc:mysql://127.0.0.1:3306/test";*/

	@Override
	public String execute() throws Exception {
		/*Class.forName(driver);
		Connection con = DriverManager.getConnection(URL, "root", "3476240");
		Statement smt = con.createStatement();*/
		Context context = new InitialContext();
		DataSource ds = (DataSource)context.lookup("java:/comp/env/jdbc/mysql");
		Connection con = ds.getConnection();
		Statement smt = con.createStatement();
		String cmd = "SELECT password FROM users WHERE username='"
				+ this.getUsername() + "'";
		ResultSet rs = smt.executeQuery(cmd);
		if (rs.next()) {
			if (this.getPassword().equals(rs.getString(1)))
				return "success";
			else 
				return "failed";
		} else
			return "failed";
		

	}

	@Override
	public void validate() {

		if (this.getUsername() == null || "".equals(this.getUsername().trim()))
			this.addFieldError("username", "UserName needed!");
		if (this.getPassword() == null || "".equals(this.getPassword().trim()))
			this.addFieldError("password", "PassWord needed!");
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}
